<template>
  <div class="table-page m-m lf">
    <GiTable
      row-key="id"
      id="channelProfit"
      v-model:columns="columns"
      :loading="loading"
      :data="tableData"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :pagination="pagination"
      @refresh="getTableData"
    >
      <template #custom-extra>
        <div>
          <a-form
            label-align="right"
            layout="inline"
            auto-label-width
            :model="listParams"
            size="small"
            class="form my-10"
          >
            <a-form-item field="inviteCode" hide-label>
              <a-input
                v-model="listParams.inviteCode"
                placeholder="用户邀请码检索"
                @press-enter="changeCurrent(1)"
              ></a-input>
            </a-form-item>
            <a-form-item hide-label class="w-42n">
              <a-select
                class="w-42n"
                v-model="listParams.orderStatus"
                placeholder="选择订单状态检索"
                @change="changeCurrent(1)"
              >
                <a-option :value="0" label="全部"></a-option>
                <a-option :value="1" label="已付款"></a-option>
                <a-option :value="10" label="已失效"></a-option>
                <a-option :value="2" label="已结算"></a-option>
                <a-option :value="5" label="违规订单"></a-option>
                <a-option :value="4" label="维权订单"></a-option>
              </a-select>
            </a-form-item>
            <a-form-item hide-label class="w-42n">
              <a-select
                class="w-42n"
                v-model="listParams.platformId"
                placeholder="选择平台类型检索"
                @change="changeCurrent(1)"
              >
                <a-option value="" label="全部"></a-option>
                <a-option
                  v-for="item in platformList"
                  :key="item.platformId"
                  :value="item.platformId"
                  :label="item.title"
                ></a-option>
              </a-select>
            </a-form-item>
            <a-form-item hide-label class="w-fit mr-10">
              <a-input-group class="flex w-full">
                <a-select class="w-36n" v-model="key2">
                  <a-option value="orderSn" label="订单号"></a-option>
                  <a-option value="tradeId" label="子订单号"></a-option>
                </a-select>
                <a-input class="w-36n" v-model="value2" @press-enter="changeCurrent(1)" placeholder="请输入" />
              </a-input-group>
            </a-form-item>
            <a-form-item hide-label>
              <div class="flex flex-a-c h-28 border-3">
                <div class="flex round-4 h-28 box-border w-fit cursor-pointer">
                  <div
                    class="flex-1 h-full flex-center nowrap px-10 box-border"
                    :class="tabIndex === 1 ? 'border-theme text-theme' : ''"
                    @click="changeData(1)"
                  >
                    今日
                  </div>
                  <div
                    class="flex-1 h-full flex-center nowrap px-10 box-border"
                    :class="tabIndex === 2 ? 'border-theme text-theme' : ''"
                    @click="changeData(2)"
                  >
                    昨日
                  </div>
                  <div
                    class="flex-1 h-full flex-center nowrap px-10 box-border"
                    :class="tabIndex === 3 ? 'border-theme text-theme' : ''"
                    @click="changeData(3)"
                  >
                    本月
                  </div>
                  <div
                    class="flex-1 h-full flex-center nowrap px-10 box-border"
                    :class="tabIndex === 4 ? 'border-theme text-theme' : ''"
                    @click="changeData(4)"
                  >
                    上月
                  </div>
                </div>
                <ms-date2
                  v-model:start="listParams.startTime"
                  v-model:end="listParams.endTime"
                  @dateChange="dataChange"
                  :allowClear="false"
                  valueF="YYYY/MM/DD"
                  :showTime="false"
                />
              </div>
            </a-form-item>
            <a-form-item hide-label>
              <a-space>
                <a-button type="primary" size="small" @click="changeCurrent(1)">
                  <template #icon>
                    <icon-search />
                  </template>
                  <template #default>查询</template>
                </a-button>
                <a-button size="small" @click="onResetSearch">
                  <template #icon>
                    <icon-sync />
                  </template>
                  <template #default>重置</template>
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>
      </template>
      <template #user="{ record }">
        <div class="flex-col">
          <div class="flex flex-a-c">
            <span>渠道方：</span>
            <span>{{ record.channelInviteCode }}</span>
            <!-- <MsUser :text="record.channelInviteCode" :inviteCode="record.channelInviteCode" /> -->
          </div>
          <div class="flex flex-a-c">
            <span>下单用户：</span>
            <span>{{ record.inviteCode }}</span>
            <!-- <MsUser :text="record.inviteCode" :inviteCode="record.inviteCode" /> -->
          </div>
          <div class="flex flex-a-c">
            <span>上级用户：</span>
            <span>{{ record.agentInviteCode }}</span>
            <!-- <MsUser :text="record.agentInviteCode" :inviteCode="record.agentInviteCode" /> -->
          </div>
        </div>
      </template>
      <template #goods="{ record }">
        <div class="flex">
          <div class="flex-col m-relative flex-1 overflow-hidden">
            <div style="min-height: 22px" class="my-2 line-h-24 text-overflow-2">
              <div class="m-absolute t-0 l-0" v-if="record.platformName">
                <a-tag color="red">{{ record.platformName }}</a-tag>
              </div>
              <div
                class="m-absolute t-0"
                :style="{ left: `${record.platformNameLength + 20}px` }"
                v-if="record.channelTagDesc"
              >
                <a-tag color="red">{{ record.channelTagDesc }}</a-tag>
              </div>
              <div
                class="m-absolute t-0"
                :style="{
                  left: `${
                    record.channelTagDescLength ? record.platformNameLength + 18 : record.platformNameLength + 24
                  }px`
                }"
                v-if="record.priceCompareStatusStr"
              >
                <a-tag color="red">{{ record.priceCompareStatusStr }}</a-tag>
              </div>
              <div
                :style="{
                  textIndent: `${
                    record.channelTagDesc
                      ? record.platformNameLength + record.priceCompareStatusLength + record.channelTagDescLength + 36
                      : record.platformNameLength + record.priceCompareStatusLength + record.channelTagDescLength + 36
                  }px`
                }"
              >
                <a-tooltip :content="record.goodsTitle">
                  <span>{{ record.goodsTitle }}</span>
                </a-tooltip>
              </div>
            </div>
            <div class="flex flex-a-c text-size-13 text808080 my-2">
              <span class="text-overflow-1 flex-1">订单号：{{ record.orderSn }}</span>
            </div>
            <div class="flex flex-a-c text-size-13 text808080 my-2">
              <span class="text-overflow-1 flex-1">子订单号：{{ record.tradeId }}</span>
            </div>
          </div>
        </div>
      </template>
      <template #order="{ record }">
        <div class="flex-col">
          <span>下单时间： </span>
          <span>{{ record.paidTime || '--' }} </span>
          <span>结算时间：</span>
          <span>{{ record.earningTime || '--' }}</span>
        </div>
      </template>
      <template #money="{ record }">
        <div class="flex-col">
          <span>商品价格：￥{{ record.goodsPrice }}</span>
          <span>付款金额：￥{{ record.payPrice }}</span>
          <span>实得佣金：￥{{ record.commission }}</span>
        </div>
      </template>
      <template #commission="{ record }">
        <div class="flex-col">
          <span>自购预估佣金：￥{{ record.userComm }}</span>
          <span>上级预估提成：￥{{ record.agentComm }}</span>
        </div>
      </template>
      <template #profit="{ record }">
        <div class="flex-col">
          <span class="font-bold text-red">￥{{ record.channelComm }}</span>
        </div>
      </template>
    </GiTable>
  </div>
</template>

<script setup>
import { Message } from '@arco-design/web-vue'
import { usePagination, usePlatform } from '@/hooks'
import { channelIncomeList } from '@/apis'
import { formatObject, deepClone, deleteEmpty } from '@/utils/common'
import dayjs from 'dayjs'
import { useUserStore } from '@/store'
const userStore = useUserStore()
const router = useRouter()
defineOptions({ name: 'channelProfit' })
const columns = ref([
  {
    title: '归属用户',
    width: 150,
    slotName: 'user'
  },
  {
    title: '商品信息',
    width: 300,
    slotName: 'goods'
  },
  {
    title: '订单时间',
    width: 180,
    slotName: 'order'
  },
  {
    title: '订单金额',
    width: 166,
    slotName: 'money'
  },
  // {
  //   title: '佣金分配',
  //   width: 180,
  //   slotName: 'commission'
  // },
  {
    title: `渠道方预估${userStore.userInfo.rewardChannelStr}`,
    width: 140,
    slotName: 'profit'
  },
  {
    title: '订单状态',
    width: 120,
    dataIndex: 'orderStatusDesc'
  }
])

const loading = ref(false)
const tableData = ref([])
const tabIndex = ref()
const listParams = reactive({
  inviteCode: undefined,
  page: 1,
  pageSize: 15,
  startTime: undefined,
  endTime: undefined,
  orderStatus: undefined,
  platformId: undefined
})
const key2 = ref('orderSn')
const value2 = ref('')
const { pagination, setTotal } = usePagination(() => getTableData(), { defaultPageSize: listParams.pageSize })

const { platformList, getPlatformList } = usePlatform()
const formatPlatform = (sourceType, key = 'title') => {
  return formatObject(unref(platformList), 'platformId', sourceType, key)
}

// 获取列表数据
const getTableData = async () => {
  try {
    loading.value = true
    listParams.page = pagination.current
    listParams.pageSize = pagination.pageSize
    const param = deepClone(listParams)
    param[key2.value] = value2.value
    if (platformList.value.length == 0) await getPlatformList()
    const res = await channelIncomeList(deleteEmpty({ ...param }))
    tableData.value = res.data.list.map((item) => {
      const platformName = formatPlatform(item.platformId)
      const priceCompareStatusStr = item.priceCompareStatus == 1 ? '自购' : ''
      const priceCompareStatusLength = priceCompareStatusStr.length * 14
      return {
        ...item,
        platformName,
        platformNameLength: platformName.length * 14,
        priceCompareStatusStr,
        priceCompareStatusLength,
        channelTagDescLength: item.channelTagDesc?.length * 14
      }
    })
    setTotal(res?.data?.total ?? 0)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getPlatformList()
  getTableData()
})

// 表格页码改变
const changeCurrent = (e) => {
  pagination.current = listParams.page = e
  getTableData()
}

const changeData = (index) => {
  tabIndex.value = index
  switch (index) {
    case 1:
      listParams.startTime = dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss')
      listParams.endTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
      break
    case 2:
      listParams.startTime = dayjs().subtract(1, 'day').startOf('day').format('YYYY-MM-DD HH:mm:ss')
      listParams.endTime = dayjs().subtract(1, 'day').endOf('day').format('YYYY-MM-DD HH:mm:ss')
      break
    case 3:
      listParams.startTime = dayjs().startOf('month').format('YYYY-MM-DD HH:mm:ss')
      listParams.endTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
      break
    case 4:
      listParams.startTime = dayjs().subtract(1, 'month').startOf('month').format('YYYY-MM-DD HH:mm:ss')
      listParams.endTime = dayjs().subtract(1, 'month').endOf('month').format('YYYY-MM-DD HH:mm:ss')
      break
  }
  changeCurrent(1)
}

const dataChange = () => {
  tabIndex.value = null
  listParams.startTime = dayjs(listParams.startTime).startOf('day').format('YYYY-MM-DD HH:mm:ss')
  listParams.endTime = dayjs(listParams.endTime).endOf('day').format('YYYY-MM-DD HH:mm:ss')
  changeCurrent(1)
}

// 重置筛选查询
const onResetSearch = () => {
  key2.value = 'orderSn'
  value2.value = ''
  listParams.inviteCode =
    listParams.startTime =
    listParams.endTime =
    listParams.orderStatus =
    listParams.platformId =
      undefined
  changeCurrent(1)
}

/* 查看详情 */
const onDetail = (item) => {
  router.push({
    path: '/channel/channelDetail',
    query: {
      id: item.id
    }
  })
}

// 改变列表中的切换按钮状态
const handleChangeStatus = async (record, str, newValue) => {
  await new Promise((resolve, reject) => {
    channelEdit({ id: record.id, [str]: newValue })
      .then(() => {
        Message.success('操作成功')
        getTableData()
        resolve(true)
      })
      .catch(() => {
        reject()
      })
  })
}
</script>

<style lang="scss" scoped>
.border-3 {
  border: 1px solid var(--color-border-3);
  border-radius: 4px;
  box-sizing: border-box;
  :deep(.arco-btn-status-normal) {
    border-color: transparent !important;
  }
}
.h-28 {
  height: 28px;
}
.ca {
  background: linear-gradient(to right, #3dadf6, #737bfc);
}
:deep(.arco-card-header) {
  border-bottom: none;
}
:deep(.arco-card-bordered) {
  border-radius: 10px;
}
</style>
